import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.swing.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class MyMouseListener extends MouseAdapter {
    JTextField jt_input;
    JTextField jt_output;
    JButton button;
    String s;
    //解析字符串与运算
    public static String out_result(String formula){
        String result=null;
        ScriptEngineManager manager = new ScriptEngineManager();       //创建一个ScriptEngineManager对象
        ScriptEngine engine = manager.getEngineByName("js");//通过ScriptEngineManager获得ScriptEngine对象
        try {
            result = engine.eval(formula).toString();  //用ScriptEngine的eval方法执行脚本
        } catch (ScriptException e) {
        }
        return result;
    }

  //构造方法
    public MyMouseListener(JTextField jt_input, JTextField jt_output, JButton button, String s) {
        this.jt_input = jt_input;
        this.jt_output = jt_output;
        this.button = button;
        this.s = s;
    }
    @Override
    public void mouseClicked(MouseEvent e) {
      if (s.equals("=")) {//求结果
          String str=jt_input.getText();
        jt_output.setText(out_result(str));
      }else if (s.equals("c")){//清空
           jt_input.setText("");
           jt_output.setText("");
      }
      else {//获取输入值到输入框
          jt_input.setText(jt_input.getText() + button.getText());//重新赋值给输入框
      }
    }

}
